from flask import request, g
from models.card_package import CardPackage
from models.store import Store
from models.user import User
from extensions import db
from utils.auth import token_required
from flask_restx import Namespace, Resource, fields
import uuid
from datetime import datetime
from models.product import Product
from models.card_consumption import CardConsumption

api = Namespace('card_packages', description='卡包管理相关接口')

# 定义API模型
card_package_model = api.model('CardPackage', {
    'id': fields.String(description='卡包ID'),
    'package_id': fields.String(description='卡包uuid'),
    'name': fields.String(required=True, description='卡包名称'),
    'card_type': fields.String(required=True, description='计费类型(comprehensive/per_use)'),
    'total_amount': fields.Float(required=True, description='总金额或次数'),
    'remaining_amount': fields.Float(description='剩余金额或次数'),
    'commission_amount': fields.Float(description='提成金额', default=0.0),
    'commission_rate': fields.Float(description='提成比例', default=0.0),
    'discount_rate': fields.Float(description='客户折扣比例', default=0.0),
    'recharge_amount': fields.Float(description='充值金额', default=0.0),
    'gift_amount': fields.Float(description='赠送金额', default=0.0),
    'expiry_date': fields.DateTime(description='有效期'),
    'user_id': fields.String(description='所属客户ID'),
    'store_id': fields.String(description='所属店铺ID'),
    'created_at': fields.DateTime(description='创建时间'),
    'updated_at': fields.DateTime(description='更新时间'),
    'is_deleted': fields.Boolean(description='是否删除')
})

base_response = api.model('BaseResponse', {
    'status': fields.String(description='响应状态'),
    'message': fields.String(description='响应消息')
})

card_package_response = api.inherit('CardPackageResponse', base_response, {
    'data': fields.Nested(card_package_model)
})

card_package_list_response = api.inherit('CardPackageListResponse', base_response, {
    'data': fields.List(fields.Nested(card_package_model))
})

@api.route('/create', strict_slashes=False)
class CardPackageCreate(Resource):
    @api.doc('创建新卡包')
    @api.expect(card_package_model)
    @api.marshal_with(card_package_response)
    @token_required
    def post(self):
        """创建新卡包"""
        data = request.get_json()
        # 检查权限：管理员或店铺管理员可以创建卡包
        store_id = data.get('store_id')
                    # 查询店铺并检查当前用户是否为店铺管理员
        store = Store.query.filter_by(
                store_id=store_id,
                manager_id=g.current_identity.user_id
            ).first()
            
        if not store and g.current_identity.roles!= 'admin':
                return {
                    'status': 'error',
                    'message': '权限不足，只有管理员或店铺管理员可以添加新卡包'
                }, 403

        new_card_package = CardPackage(
            package_id=str(uuid.uuid4()),
            name=data['name'],
            card_type=data['card_type'],
            total_amount=data['total_amount'],
            expiry_date=datetime.fromisoformat(data['expiry_date'].replace('Z', '+00:00')) if data.get('expiry_date') else None,
            store_id=data.get('store_id'),
            commission_rate=float(data.get('commission_rate')) if data.get('commission_rate') not in [None, ''] else None,
            discount_rate=float(data.get('discount_rate')) if data.get('discount_rate') not in [None, ''] else None,
            recharge_amount=float(data.get('recharge_amount')) if data.get('recharge_amount') not in [None, ''] else None,
            gift_amount=float(data.get('gift_amount')) if data.get('gift_amount') not in [None, ''] else None
        )
        
        db.session.add(new_card_package)
        db.session.commit()
        
        return {
            'status': 'success',
            'message': '卡包创建成功',
            'data': new_card_package.to_dict()
        }, 201

@api.route('/list', strict_slashes=False)
class CardPackageList(Resource):
    @api.doc('获取卡包列表', params={
        'store_id': '店铺ID（可选）',
        'billing_type': '计费类型（可选）',
        'name': '卡包名称（可选，模糊查询）'
    })
    @api.marshal_with(card_package_list_response)
    @token_required
    def get(self):
        """获取卡包列表"""
        from sqlalchemy import or_
        
        store_id = request.args.get('store_id')
        user_id = request.args.get('user_id')
        
        # 基础查询条件
        query = CardPackage.query.filter_by(is_deleted=False)
        
        if store_id:
            # 构建查询条件
            if user_id:
                # 如果提供了user_id，查询该店铺下该用户的卡包
                query = query.filter(
                    CardPackage.store_id == store_id,
                    CardPackage.user_id == user_id
                )
            else:
                # 如果没提供user_id，查询该店铺下公共卡包(user_id为null)
                query = query.filter(
                    CardPackage.store_id == store_id,
                    CardPackage.user_id.is_(None)
                )
            
        # 其他过滤条件
        card_type = request.args.get('card_type')
        if card_type:
            query = query.filter(CardPackage.card_type == card_type)
            
        name = request.args.get('name')
        if name:
            query = query.filter(CardPackage.name.like(f'%{name}%'))
        
        # 按创建时间倒序排序
        card_packages = query.order_by(CardPackage.created_at.desc()).all()
        
        return {
            'status': 'success',
            'message': '获取成功',
            'data': [package.to_dict() for package in card_packages]
        }, 200

@api.route('/detail/<package_id>', strict_slashes=False)
class CardPackageDetail(Resource):
    @api.doc('获取卡包详情')
    @api.marshal_with(card_package_response)
    @token_required
    def get(self, package_id):
        """获取卡包详情"""
        card_package = CardPackage.query.filter_by(
            package_id=package_id,
            is_deleted=False
        ).first_or_404()
        
        return {
            'status': 'success',
            'message': '获取成功',
            'data': card_package.to_dict()
        }, 200

@api.route('/update/<package_id>', strict_slashes=False)
class CardPackageUpdate(Resource):
    @api.doc('更新卡包信息')
    @api.expect(card_package_model)
    @api.marshal_with(card_package_response)
    @token_required
    def post(self, package_id):
        """更新卡包信息"""
        card_package = CardPackage.query.filter_by(
            package_id=package_id,
            is_deleted=False
        ).first_or_404()
        
        data = request.get_json()
        
        if 'name' in data:
            card_package.name = data['name']
        if 'billing_type' in data:
            card_package.billing_type = data['billing_type']
        if 'total_amount' in data:
            card_package.total_amount = data['total_amount']     
        if 'commission_amount' in data:
            card_package.commission_amount = data['commission_amount']
        if 'commission_rate' in data:
            card_package.commission_rate = data['commission_rate']
            # 如果是默认卡包，同步更新所有关联卡包的提成比例
            if card_package.card_type == 'default':
                CardPackage.query.filter_by(
                    parent_card_package_id=card_package.package_id,
                    is_deleted=False
                ).update({
                    'commission_rate': data['commission_rate']
                })
        if 'recharge_amount' in data:
            card_package.recharge_amount = data['recharge_amount']
            card_package.remaining_amount = data['total_amount']
        if 'gift_amount' in data:
            card_package.gift_amount = data['gift_amount']  
        if 'discount_rate' in data:
            card_package.discount_rate = data['discount_rate']    
        if 'expiry_date' in data:
            card_package.expiry_date = datetime.fromisoformat(data['expiry_date'].replace('Z', '+00:00')) if data.get('expiry_date') else None
         
        db.session.commit()
        
        return {
            'status': 'success',
            'message': '卡包信息更新成功',
            'data': card_package.to_dict()
        }, 200

@api.route('/delete/<package_id>', strict_slashes=False)
class CardPackageDelete(Resource):
    @api.doc('删除卡包')
    @api.marshal_with(base_response)
    @token_required
    def post(self, package_id):
        """删除卡包（软删除）"""
        card_package = CardPackage.query.filter_by(
            package_id=package_id,
            is_deleted=False
        ).first_or_404()
        
        card_package.is_deleted = True
        db.session.commit()
        
        return {
            'status': 'success',
            'message': '卡包删除成功'
        }, 200

@api.route('/recharge', strict_slashes=False)
class CardPackageRecharge(Resource):
    @api.doc('卡包充值')
    @api.expect(api.model('RechargeRequest', {
        'store_id': fields.String(required=True, description='店铺ID'),
        'user_id': fields.String(required=True, description='客户ID'),
        'package_id': fields.String(required=True, description='卡包ID'),
        'staff_id': fields.String(required=True, description='销售员ID'),
        'recharge_amount': fields.Float(required=True, description='充值金额'),
        'gift_amount': fields.Float(description='赠送金额', default=0.0),
        'discount_rate': fields.Float(description='客户折扣比例', default=1.0)
    }))
    @api.marshal_with(card_package_response)
    @token_required
    def post(self):
        """卡包充值"""
        data = request.get_json()
        
        # 校验必填参数
        required_fields = ['store_id', 'user_id', 'package_id', 'recharge_amount','staff_id']
        for field in required_fields:
            if field not in data:
                return {
                    'status': 'error',
                    'message': f'缺少必填字段: {field}'
                }, 400
        
        try:
            # 查询卡包
            card_package = CardPackage.query.filter_by(
                package_id=data['package_id'],
                store_id=data['store_id'],
                user_id=data['user_id'],
                is_deleted=False
            ).first()
            # 检查店铺是否存在
            store = Store.query.filter_by(store_id=data['store_id'], is_deleted=False).first_or_404()
            user = User.query.filter_by(user_id=data['user_id'], is_deleted=False).first_or_404()
            
            if not card_package:
                return {
                    'status': 'error',
                    'message': '卡包不存在或不属于该客户'
                }, 404
            
            # 更新卡包金额
            # card_package.recharge_amount = (card_package.recharge_amount or 0) + data['recharge_amount']
            # card_package.gift_amount = (card_package.gift_amount or 0) + (data.get('gift_amount') or 0)
            
            # 根据卡包类型更新不同字段
            if card_package.card_type == 'default' or card_package.card_type == 'comprehensive':
                # 综合卡：更新总金额和剩余金额
                card_package.total_amount = card_package.total_amount + data['recharge_amount'] + (data.get('gift_amount') or 0)
                card_package.remaining_amount = (card_package.remaining_amount or 0) + data['recharge_amount'] + (data.get('gift_amount') or 0)
            # 更新折扣率
            if 'discount_rate' in data:
                card_package.discount_rate = data['discount_rate']

            # 记录交易详情，提成，分红记录
            transactions = []
            curent_user = g.current_identity
            staff_user=User.query.filter_by(user_id=data['staff_id'],is_deleted=False).first_or_404()
            # 现金支付记录 (交易类型1-卡包充值)
            transactions.append((1, 1, data['recharge_amount'],staff_user.id,None))
            
            # 提成记录 (交易类型5-提成支出)
            commission = round(data['recharge_amount'] * card_package.commission_rate, 2)
            transactions.append((5, 0, commission,staff_user.id,None))

            # 计算剩余余额（收入减去支出）
            total_income = data['recharge_amount']
            total_expense = commission
            remaining_balance = round(total_income - total_expense, 2)
            
            # 无论余额是正是负，都需要按照股东比例分配或分摊
            # 查询店铺中有股份的用户（排除平台股东）
            from models.user_store import UserStore
            
            # 查询店铺中有股份的用户（排除平台股东）
            store_shareholders = db.session.query(UserStore, User.id).join(
                User, UserStore.user_id == User.user_id
            ).filter(
                UserStore.store_id == data['store_id'],
                UserStore.equity_ratio > 0,
                UserStore.role != 'platform_shareholder',
                User.is_deleted == False
            ).all()
            
            # 分配给普通股东的总金额
            distributed_amount = 0
            
            # 为每个股东生成分配记录
            for shareholder,staff_id in store_shareholders:
                if shareholder.equity_ratio > 0:
                    # 直接使用数据库中的股份比例计算
                    shareholder_amount = round(remaining_balance * shareholder.equity_ratio, 2)
                    
                    # 无论金额是正是负都记录
                    # 如果是正数，表示分红；如果是负数，表示分摊成本
                    amount = shareholder_amount              
                
                    # 创建记录（店铺支出）
                    transactions.append((9, 0, amount, staff_id, shareholder.equity_ratio))
                    distributed_amount += shareholder_amount
            
            # 计算分配后剩余的金额
            platform_remaining = round(remaining_balance - distributed_amount, 2)
            
            # 无论是盈利还是亏损，剩余部分都分配给平台股东
            # 查询平台股东
            platform_shareholders = db.session.query(UserStore, User.id).join(
                User, UserStore.user_id == User.user_id
            ).filter(
                UserStore.store_id == data['store_id'],
                UserStore.role == 'platform_shareholder',
                User.is_deleted == False
            ).all()
            
            if platform_shareholders and platform_remaining != 0:
                # 如果有多个平台股东，按照他们的股份比例分配
                platform_total_equity = sum(ps[0].equity_ratio for ps in platform_shareholders)
                for platform_shareholder,staff_id in platform_shareholders:
                    if platform_total_equity > 0:
                        # 按比例分配平台股东的份额
                        platform_share = round(platform_remaining * (platform_shareholder.equity_ratio / platform_total_equity), 2)
                    else:
                        # 如果没有设置股份比例，平均分配
                        platform_share = round(platform_remaining / len(platform_shareholders), 2)
                    
                    # 确定收支类型
                    # 如果是负数，记为收入（分摊成本）
                    amount = platform_share
                    # 创建平台股东分配记录
                    transactions.append((10, 0, amount,staff_id,platform_shareholder.equity_ratio))

            for transaction_type, income_type, amount_used, staff_id,equity_ratio in transactions:
                consumption = CardConsumption(
                    transaction_type=transaction_type,
                    income_type=income_type,
                    amount_used=amount_used,
                    staff_id=staff_id,
                    equity_ratio=equity_ratio,
                    store_id=store.id,
                    card_package_id=card_package.id,
                    user_id=user.id,
                    product_id=None,
                    consumption_date=datetime.now(),
                    order_id=None,
                    card_type=card_package.card_type,
                    handle_user_id=curent_user.id
                )
                db.session.add(consumption)

            db.session.commit()
            
            return {
                'status': 'success',
                'message': '卡包充值成功',
                'data': card_package.to_dict()
            }, 200
            
        except Exception as e:
            db.session.rollback()
            return {
                'status': 'error',
                'message': f'卡包充值失败: {str(e)}'
            }, 500
